<style>
<!--
.alloc-table {
	font-size: 8pt;
	text-align: right;
}
-->
</style>
<div id="tab-database">
	<button onclick="javascript:askDatabaseInfo()" class="ui-button-text-icon">
		Refresh <img border="0" alt="Refresh" src="images/execute.png" align="top" />
	</button>
	<div id="tabs-db">
		<ul>
			<li><a href="#tab-db-schema"><span>Schema</span> </a></li>
			<li><a href="#tab-db-structure"><span>Structure</span> </a></li>
			<li><a href="#tab-db-allocation"><span>Allocation</span> </a></li>
			<li><a href="#tab-db-security"><span>Security</span> </a></li>
			<li><a href="#tab-db-config"><span>Configuration</span> </a></li>
			<li><a href="#tab-db-importExport"><span>Import\Export</span> </a></li>
		</ul>
		<div id="tab-db-schema">
			<table style="width: 100%;" cellpadding="5">
				<tr>
					<td valign="top">
						<table width="100%">
							<tr>
								<td width="600">
									<table id="databaseClasses" cellspacing="0" cellpadding="5" border="1" width="100%">
									</table>
								</td>
								<td valign="top" align="left" width="150">
									<table>
										<tr>
											<td>
												<button id="queryClass" class="ui-button-text-icon" style="text-align: left">
													Query <img border="0" alt="Query" src="images/execute.png" align="top" />
												</button>
											</td>
										</tr>
										<tr>
											<td>
												<button id="createObject" class="ui-button-text-icon" style="text-align: left">
													Create object <img border="0" alt="Create object" src="images/set.png" align="top" />
												</button>
											</td>
										</tr>
										<tr>
											<td>
												<button id="deleteClass" class="ui-button-text-icon" style="text-align: left">
													Delete class <img border="0" alt="Delete record" src="images/delete.png" align="top" />
												</button>
											</td>
										</tr>
									</table>
								</td>
								<td valign="top" class="help">Select the class to display the properties associated. Each class can store its records into one or
									multiple <b>Clusters</b> (see "Structure" tab). A class can be <b>schema-less</b> (has no properties), <b>schema-full</b> (all properties as
									mandatories) or with a <b>partial schema</b>.
								</td>
							</tr>
							<tr>
								<td valign="top" align="left">
									<table>
										<tr>
											<td>
												<button id="addClass" class="ui-button-text-icon" style="text-align: left">
													Add class <img border="0" alt="New record" src="images/add.png" align="top" />
												</button>
											</td>
											<td>
										</tr>
									</table>
								</td>
							</tr>
						</table>
					</td>
				</tr>
				<tr>
					<td valign="top">
						<table width="100%">
							<tr>
								<td valign="top" width="850">
									<table id="classProperties" style="width: 100%;" cellspacing="0" cellpadding="5" border="1">
									</table>
								</td>
								<td valign="top" align="left">
									<table>
										<tr>
											<td>
												<button id="deleteProperty" class="ui-button-text-icon" style="text-align: left">
													Delete property <img border="0" alt="Delete record" src="images/delete.png" align="top" />
												</button>
											</td>
										</tr>
									</table>
								</td>
							</tr>
							<tr>
								<td valign="top" align="left">
									<table>
										<tr>
											<td>
												<button id="addProperty" class="ui-button-text-icon" style="text-align: left">
													Add property <img border="0" alt="New record" src="images/add.png" align="top" />
												</button>
											</td>
										</tr>
									</table>
								</td>
							</tr>
						</table>
					</td>
				</tr>
                <tr>
                    <td valign="top">
                        <table width="100%">
                            <tr>
                                <td valign="top" width="850">
                                    <table id="classIndexes" style="width: 100%;" cellspacing="0" cellpadding="5" border="1">
                                    </table>
                                </td>
                                <td valign="top" align="left">
                                    <table>
                                        <tr>
                                            <td>
                                                <button id="deleteIndex" class="ui-button-text-icon" style="text-align: left">
                                                    Delete index <img border="0" alt="Delete index" src="images/delete.png" align="top" />
                                                </button>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                            <tr>
                                <td valign="top" align="left">
                                    <table>
                                        <tr>
                                            <td>
                                                <button id="addIndex" class="ui-button-text-icon" style="text-align: left">
                                                    Add index <img border="0" alt="Add index" src="images/add.png" align="top" />
                                                </button>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
			</table>
		</div>
		<div id="tab-db-structure">
			<table style="width: 100%;" cellpadding="5">
				<tr>
					<td valign="top" class="help"><b><a href="http://code.google.com/p/orient/wiki/Concepts#Cluster">Clusters</a> </b> are sets of records
						grouped by a mean. Any mean you want to assign. You can use a Cluster like a Table of the Relational DBMS world, namely to group records of the
						same type. Or you could want to group records by different logics. <br /> <br /> There are two kinds of clusters: <b><a
							href="http://code.google.com/p/orient/wiki/Concepts#Local_Physical_Cluster">Physical</a> </b> and <b><a
							href="http://code.google.com/p/orient/wiki/Concepts#Logical_Cluster">Logical</a> </b>. The first one uses ad-hoc files to speed up the I/O while
						the second one saves more space but it's slower. The suggestion is to use Physical Clusters for the records accessed often and where you need
						light speed.</td>
				</tr>
				<tr>
					<td valign="top" width="500">
						<table id="databaseClusters" style="width: 100%;" cellspacing="0" cellpadding="5" border="1">
						</table>
					</td>
				</tr>
				<tr>
					<td valign="top" align="left">
						<table>
							<tr>
								<td>
									<button id="addPhysicalCluster" class="ui-button-text-icon" style="text-align: left">
										Add Physical Cluster <img border="0" alt="Add Physical Cluster" src="images/add.png" align="top" />
									</button>
								</td>
								<td>
									<button id="addLogicalCluster" class="ui-button-text-icon" style="text-align: left">
										Add Logical Cluster <img border="0" alt="Add Logical Cluster" src="images/add.png" align="top" />
									</button>
								</td>
								<td>
									<button id="removeCluster" class="ui-button-text-icon" style="text-align: left">
										Remove Cluster <img border="0" alt="Remove Cluster" src="images/delete.png" align="top" />
									</button>
								</td>
							</tr>
						</table>
					</td>
				</tr>
				<tr>
					<td valign="top" class="help"><b><a href="http://code.google.com/p/orient/wiki/Concepts#Data_Segment">Data segments</a> </b> are the
						segments that contain data pointed by Clusters.</td>
				</tr>
				<tr>
					<td valign="top" width="500">
						<table id="databaseDataSegments" style="width: 100%;" cellspacing="0" cellpadding="5" border="1">
						</table>
					</td>
				</tr>
				<tr>
					<td valign="top" class="help"><b>Tx Segment</b> handles the transaction log for the entire database. It's used in Transactions.</td>
				</tr>
				<tr>
					<td valign="top" width="500">
						<table id="databaseTxSegment" style="width: 100%;" cellspacing="0" cellpadding="5" border="1">
						</table>
					</td>
				</tr>
			</table>
		</div>
		<div id="tab-db-allocation">
			<table style="width: 100%;" cellpadding="5">
				<tr>
					<td valign="top" class="help"><canvas id="allocation-canvas" width="850" height="500"></canvas></td>
					<td>
					<td valign="top">
						<table>
							<tr>
								<td>
									<table cellpadding="5" cellspacing="5">
										<tr>
											<td colspan="2">Legenda:</td>
										</tr>
										<tr>
											<td>Data:</td>
											<td id='data-value' style='background-color: #00FF00' align="center">?</td>
										</tr>
										<tr>
											<td>Free:</td>
											<td id='holes-value' style='background-color: #FF0000' align="center">?</td>
										</tr>
									</table>
								</td>
							</tr>
							<tr>
								<td>
									<table id='allocation-data' cellpadding="2" cellspacing="2" width="100%" border="0"></table>
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
		</div>
		<div id="tab-db-security">
			<div id="tabs-security">
				<ul>
					<li><a href="#tab-security-users"><span>Users</span> </a></li>
					<li><a href="#tab-security-roles"><span>Roles</span> </a></li>
				</ul>
				<div id="tab-security-users">
					<table id="databaseUsers" style="width: 100%;" cellspacing="0" cellpadding="5" border="1">
					</table>
				</div>
				<div id="tab-security-roles">
					<table style="width: 100%;" cellpadding="5" cellspacing="0">
						<tr>
							<td>
								<table id="databaseRoles" style="width: 100%;" cellspacing="0" cellpadding="5" border="1">
								</table>
							</td>
							<td>
								<table id="databaseRolesRules" style="width: 100%;" cellspacing="0" cellpadding="5" border="1">
								</table>
							</td>
						</tr>
					</table>
				</div>
			</div>
		</div>
		<div id="tab-db-config">
			<table style="width: 100%;" cellpadding="5">
				<tr>
					<td valign="top">
						<table id="databaseConfig" style="width: 100%;" cellspacing="0" cellpadding="5" border="1">
						</table>
					</td>
					<td valign="top" class="help"></td>
				</tr>
				<tr>
					<td valign="top">
						<table id="databaseConfigProperties" style="width: 100%;" cellspacing="0" cellpadding="5" border="1">
						</table>
					</td>
					<td valign="top" class="help"></td>
				</tr>
			</table>
		</div>
		<div id="tab-db-importExport">
			<table style="width: 100%;" cellpadding="5">
				<tr>
					<td valign="top">
						<button id="exportDatabase" class="ui-button-text exportButton" style="text-align: left; width: 100%;" >Export Database</button>
					</td>
					<td valign="top" class="help">Orient server can export databases as JSON data. Click the <b>Export Database</b> button to download a gzip compressed file containing said JSON file.</td>
				</tr>
				<tr>
					<td valign="top">
						<div id="importDatabaseContainer">
							<form id="importDatabase" class="file_upload"
								enctype="multipart/form-data" method="POST">
								<input type="file" multiple="" name="databaseFile" />
								<button type="button">Upload</button>
								<div class="file_upload_label">Import Database</div>
							</form>
							<table id="importFileUploadTable">
							</table>
							<table id="importFileDownloadTable">
							</table>
						</div>
					</td>
					<td valign="top" class="help">Import a previously exported
						database. JSON data.<br /> <b>Requirements:</b>
						<ul>
							<li>Supported only JSON text file types.</li>
							<li>The default max request content lenght is
								100000 bytes.<br />To change it add the following entry (value expressed in bytes) in the
								<b>orientdb-server-config.xml</b>:<br> <code>&lt;entry name=&#34;network.http.maxLength&#34; value=&#34;&#34; &#47;&gt;</code></li>
						</ul>
					</td>
				</tr>
			</table>
		</div>
	</div>
</div>

<script language="javascript">
	function showDatabaseInfo() {
		fillDynaTable($('#databaseClusters'), "Clusters", [ 'id', 'name',
				'type', 'records', 'size', 'filled', 'maxSize', 'files' ], [ {
			name : 'id',
			index : 'id',
			width : '30px',
			editable : false
		}, {
			name : 'name',
			index : 'name',
			width : '100px',
			editable : false
		}, {
			name : 'type',
			index : 'type',
			width : '80px',
			editable : false
		}, {
			name : 'records',
			index : 'records',
			width : '80px',
			editable : false
		}, {
			name : 'size',
			index : 'size',
			width : '80px',
			editable : false
		}, {
			name : 'filled',
			index : 'filled',
			width : '80px',
			editable : false
		}, {
			name : 'maxSize',
			index : 'maxSize',
			width : '80px',
			editable : false
		}, {
			name : 'files',
			index : 'files',
			width : '450px',
			editable : false
		} ], databaseInfo['clusters'], {
			sortname : 'id',
			editurl : getStudioURL('clusters')
		});

		$("#addPhysicalCluster").click(function() {
			jQuery("#databaseClusters").jqGrid('editGridRow', "newp", {
				height : 320,
				reloadAfterSubmit : false,
				closeOnEscape : true,
				closeAfterAdd : true,
				editData : [ selectedClassName ],
				afterSubmit : function(response, postdata) {
					jQuery("#output").val(response.responseText);
					return true;
				}
			});
		});
		$("#addLogicalCluster").click(function() {
			jQuery("#databaseClusters").jqGrid('editGridRow', "newl", {
				height : 320,
				reloadAfterSubmit : false,
				closeOnEscape : true,
				closeAfterAdd : true,
				editData : [ selectedClassName ],
				afterSubmit : function(response, postdata) {
					jQuery("#output").val(response.responseText);
					return true;
				}
			});
		});
		$("#removeCluster").click(
				function() {
					var selectedRow = jQuery("#databaseClusters").jqGrid(
							'getGridParam', 'selrow');
					if (selectedRow != null) {
						jQuery("#databaseClusters").jqGrid(
								'delGridRow',
								selectedRow,
								{
									reloadAfterSubmit : false,
									closeOnEscape : true,
									delData : [ selectedClassName ],
									afterSubmit : function(response, postdata) {
										jQuery("#output").val(
												response.responseText);
										return [ true, response.responseText ];
									}
								});
					} else
						alert("Please select the cluster to delete!");
				});

		fillDynaTable($('#databaseDataSegments'), "Data Segments", [ 'id',
				'name', 'size', 'filled', 'maxSize', 'files' ], [ {
			name : 'id',
			index : 'id',
			width : '30px',
			editable : false
		}, {
			name : 'name',
			index : 'name',
			width : '100px',
			editable : false
		}, {
			name : 'size',
			index : 'size',
			width : '80px',
			editable : false
		}, {
			name : 'filled',
			index : 'filled',
			width : '80px',
			editable : false
		}, {
			name : 'maxSize',
			index : 'maxSize',
			width : '80px',
			editable : false
		}, {
			name : 'files',
			index : 'files',
			width : '600px',
			editable : false
		} ], databaseInfo['dataSegments'], {
			height : '40px'
		});

		fillDynaTable($('#databaseTxSegment'), "Tx Segment", [ 'totalLogs',
				'size', 'filled', 'maxSize', 'file' ], [ {
			name : 'totalLogs',
			index : 'Total Logs',
			width : '100px',
			editable : false
		}, {
			name : 'size',
			index : 'Size',
			width : '80px',
			editable : false
		}, {
			name : 'filled',
			index : 'Filled',
			width : '80px',
			editable : false
		}, {
			name : 'maxSize',
			index : 'Max Size',
			width : '80px',
			editable : false
		}, {
			name : 'file',
			index : 'File',
			width : '600px',
			editable : false
		} ], databaseInfo['txSegment'], {
			height : '25px'
		});

		fillDynaTable($('#databaseUsers'), "Users", [ 'name', 'roles' ], null,
				databaseInfo['users']);
		fillDynaTable($('#databaseRolesRules'), "Rules", [ 'Name', 'Create',
				'Read', 'Update', 'Delete' ], [ {
			name : 'name',
			index : 'name',
			formatter : 'text',
			edittype : 'text',
			editable : false
		}, {
			name : 'create',
			index : 'create',
			formatter : 'checkbox',
			edittype : 'checkbox',
			editable : true
		}, {
			name : 'read',
			index : 'read',
			formatter : 'checkbox',
			edittype : 'checkbox',
			editable : true
		}, {
			name : 'update',
			index : 'update',
			formatter : 'checkbox',
			edittype : 'checkbox',
			editable : true
		}, {
			name : 'delete',
			index : 'delete',
			formatter : 'checkbox',
			edittype : 'checkbox',
			editable : true
		} ], null);
		fillDynaTable(
				$('#databaseRoles'),
				"Roles",
				[ 'name', 'mode' ],
				null,
				databaseInfo['roles'],
				{
					sortname : 'name',
					onSelectRow : function(roleRowNum) {
						var role = databaseInfo['roles'][roleRowNum - 1];
						fillDynaTableRows($('#databaseRolesRules'), role.rules);
					}
				});

		classEnumeration = ":;";
		for (cls in databaseInfo['classes']) {
			if (classEnumeration.length > 2)
				classEnumeration += ";";
			classEnumeration += databaseInfo['classes'][cls].name + ":"
					+ databaseInfo['classes'][cls].name;
		}

		jQuery($('#classProperties')).jqGrid('GridUnload');
		fillDynaTable(
				$('#classProperties'),
				"Properties",
				[ 'name', 'type', 'linkedType', 'linkedClass', 'mandatory',
						'notNull', 'min', 'max' ],
				[
						{
							name : 'name',
							index : 'name',
							width : 180,
							editable : true,
							editrules : {
								required : true
							},
							formoptions : {
								elmprefix : '(*)'
							}
						},
						{
							name : 'type',
							index : 'type',
							width : 100,
							edittype : "select",
							editoptions : {
								value : ":;BINARY:BINARY;BOOLEAN:BOOLEAN;EMBEDDED:EMBEDDED;EMBEDDEDLIST:EMBEDDEDLIST;EMBEDDEDMAP:EMBEDDEDMAP;EMBEDDEDSET:EMBEDDEDSET;DECIMAL:DECIMAL;FLOAT:FLOAT;DATE:DATE;DATETIME:DATETIME;DOUBLE:DOUBLE;INTEGER:INTEGER;LINK:LINK;LINKLIST:LINKLIST;LINKMAP:LINKMAP;LINKSET:LINKSET;LONG:LONG;SHORT:SHORT;STRING:STRING"
							},
							editable : true,
							editrules : {
								required : true
							},
							formoptions : {
								elmprefix : '(*)'
							}
						},
						{
							name : 'linkedType',
							index : 'linkedType',
							width : 150,
							edittype : "select",
							editoptions : {
								value : ":;BINARY:BINARY;BOOLEAN:BOOLEAN;EMBEDDED:EMBEDDED;EMBEDDEDLIST:EMBEDDEDLIST;EMBEDDEDMAP:EMBEDDEDMAP;EMBEDDEDSET:EMBEDDEDSET;DECIMAL:DECIMAL;FLOAT:FLOAT;DATE:DATE;DATETIME:DATETIME;DOUBLE:DOUBLE;INTEGER:INTEGER;LINK:LINK;LINKLIST:LINKLIST;LINKMAP:LINKMAP;LINKSET:LINKSET;LONG:LONG;SHORT:SHORT;STRING:STRING"
							},
							editable : true
						}, {
							name : 'linkedClass',
							index : 'linkedClass',
							width : 150,
							edittype : "select",
							editoptions : {
								value : classEnumeration
							},
							editable : true
						}, {
							name : 'mandatory',
							index : 'mandatory',
							width : 90,
							formatter : 'checkbox',
							edittype : 'checkbox',
							editable : true
						}, {
							name : 'notNull',
							index : 'notNull',
							width : 80,
							formatter : 'checkbox',
							edittype : 'checkbox',
							editable : true
						}, {
							name : 'min',
							index : 'min',
							width : 120,
							editable : true
						}, {
							name : 'max',
							index : 'max',
							width : 120,
							editable : true
						} ], null, {
					editurl : getStudioURL('classProperties'),
					sortname : 'name'
				});

		$("#addProperty")
				.click(
						function() {
							if (selectedClassName == null) {
								alert("Please select class for which property is going to be added !");
								return;
							}

							jQuery("#classProperties").jqGrid(
									'editGridRow',
									"new",
									{
										height : 320,
										reloadAfterSubmit : false,
										closeOnEscape : true,
										closeAfterAdd : true,
										editData : [ selectedClassName ],
										afterSubmit : function(response,
												postdata) {
											jQuery("#output").val(
													response.responseText);
											return true;
										}
									});
						});
		$("#deleteProperty").click(
				function() {
					var selectedRow = jQuery("#classProperties").jqGrid(
							'getGridParam', 'selrow');
					if (selectedRow != null) {
						var propName = jQuery('#classProperties').jqGrid(
								'getRowData', selectedRow)["name"];
						jQuery("#classProperties").jqGrid(
								'delGridRow',
								selectedRow,
								{
									reloadAfterSubmit : false,
									closeOnEscape : true,
									delData : [ selectedClassName, propName ],
									afterSubmit : function(response, postdata) {
										jQuery("#output").val(
												response.responseText);
										return [ true, response.responseText ];
									}
								});
					} else
						alert("Please select the property to delete!");
				});

        jQuery($('#classIndexes')).jqGrid('GridUnload');
        fillDynaTable(
                $('#classIndexes'),
                "Indexes",
                [ 'name', 'type', 'properties' ],
                [
                        {
                            name : 'name',
                            index : 'name',
                            width : 180,
                            editable : true,
                            editrules : {
                                required : true
                            },
                            formoptions : {
                                elmprefix : '(*)'
                            }
                        },
                        {
                            name : 'type',
                            index : 'type',
                            width : 100,
                            edittype : "select",
                            editoptions : {
						    value : ":;Unique:Unique;Not unique:Not Unique"
                            },
							editable : true,
                            editrules : {
                                required : true
                            },
                            formoptions : {
                                elmprefix : '(*)'
                            }
                        },
                        {
                            name :'fields',
                            width : 200,
                            editable : true,
                            editrules : {
                                required : true
                            },
                            editoptions : {
                                dataInit : function(elem) {
                                   $(elem).attr("title", "Add properties using comma as separator");
                                   $(elem).tooltip({
                                        // place tooltip on the right edge
                                        position: "center right",
                                        // a little tweaking of the position
                                        offset: [-2, 10],
                                        // use the built-in fadeIn/fadeOut effect
                                        effect: "fade"
                                    });
                                }
                            },
                            formoptions : {
                                elmprefix : '(*)'
                            }
                        }
                ], null, {
                    editurl : getStudioURL('classIndexes'),
                    sortname : 'name'
                });

        var addIndexDialogId;
        $("#addIndex").click(function() {
            if(selectedClassName == null) {
                alert("Please select class for which index is going to be added !");
                return;
            }

            jQuery("#classIndexes").jqGrid('editGridRow', "new", {
                height : 200,
                reloadAfterSubmit : false,
                closeOnEscape : true,
                closeAfterAdd : true,
                editData : [ selectedClassName ],
                afterSubmit : function(response, postdata) {
                    jQuery("#output").val(response.responseText);

                    var textlist = $(addIndexDialogId).find('[type="text"]').each(function (index, element) {
                        var tooltip = $(element).data("tooltip");
                        if (tooltip)
                            tooltip.hide();
                    });

                    return true;
                },

                onClose : function() {
                    var textlist = $(addIndexDialogId).find('[type="text"]').each(function (index, element) {
                        var tooltip  = $(element).data("tooltip");
                        if(tooltip)
                            tooltip.hide();
                    });
                },
                onInitializeForm : function(formId) {
                    addIndexDialogId = formId;
                }
            });
        });
        $("#deleteIndex").click(
                function() {
                    var selectedRow = jQuery("#classIndexes").jqGrid(
                            'getGridParam', 'selrow');
                    if (selectedRow != null) {
                        var indexName = jQuery('#classIndexes').jqGrid(
                                'getRowData', selectedRow)["name"];
                        jQuery("#classIndexes").jqGrid(
                                'delGridRow',
                                selectedRow,
                                {
                                    reloadAfterSubmit : false,
                                    closeOnEscape : true,
                                    delData : [ selectedClassName, indexName ],
                                    afterSubmit : function(response, postdata) {
                                        jQuery("#output").val(
                                                response.responseText);
                                        return [ true, response.responseText ];
                                    }
                                });
                    } else
                        alert("Please select the index to delete!");
                });


		fillDynaTable(
				$('#databaseClasses'),
				"Classes",
				[ 'name', 'superClass', 'alias', 'clusters', 'defaultCluster',
						'records' ],
				[ {
					name : 'name',
					index : 'name',
					width : 280,
					editable : true,
					editrules : {
						required : true
					},
					formoptions : {
						elmprefix : '(*)'
					}
				}, {
					name : 'superClass',
					index : 'superClass',
					width : 150,
					editable : true,
					formoptions : {
						elmprefix : '(*)'
					}
				}, {
					name : 'alias',
					index : 'alias',
					width : 80,
					editable : true,
					formoptions : {
						elmprefix : '(*)'
					}
				}, {
					name : 'clusters',
					index : 'clusters',
					width : 80,
					editable : false
				}, {
					name : 'defaultCluster',
					index : 'defaultCluster',
					width : 80,
					editable : false
				}, {
					name : 'records',
					index : 'records',
					width : 150,
					editable : false
				} ],
				databaseInfo['classes'],
				{
					sortname : 'id',
					editurl : getStudioURL('classes'),
					onSelectRow : function(classRowNum) {
						selectedClassName = databaseInfo['classes'][classRowNum - 1].name;
						fillDynaTableRows(
								$('#classProperties'),
								databaseInfo['classes'][classRowNum - 1]['properties']);
                        fillDynaTableRows(
								$('#classIndexes'),
								databaseInfo['classes'][classRowNum - 1]['indexes']);
					}
				});

		$("#addClass").click(function() {
			jQuery("#databaseClasses").jqGrid('editGridRow', "new", {
				height : 320,
				reloadAfterSubmit : false,
				closeOnEscape : true,
				closeAfterAdd : true,
				editData : [ selectedClassName ],
				afterSubmit : function(response, postdata) {
					jQuery("#output").val(response.responseText);
					return true;
				}
			});
		});
		$("#deleteClass").click(
				function() {
					var selectedRow = jQuery("#databaseClasses").jqGrid(
							'getGridParam', 'selrow');
					if (selectedRow != null) {
						jQuery("#databaseClasses").jqGrid(
								'delGridRow',
								selectedRow,
								{
									reloadAfterSubmit : false,
									closeOnEscape : true,
									delData : [ selectedClassName ],
									afterSubmit : function(response, postdata) {
										jQuery("#output").val(
												response.responseText);
										return [ true, response.responseText ];
									}
								});
					} else
						alert("Please select the class to delete!");
				});
		$("#queryClass").click(
				function() {
					var selectedRow = jQuery("#databaseClasses").jqGrid(
							'getGridParam', 'selrow');
					if (selectedRow != null) {
						selObject = jQuery('#databaseClasses').jqGrid(
								'getRowData', selectedRow)["name"];

						controller.parameter('queryLoad', function() {
							queryEditor.setCode("select from " + selObject);
							executeQuery();
							queryEditor.focus();
						});

						controller.loadFragment("panelQuery.htm");
					}
				});
		$("#createObject").click(
				function() {
					var selectedRow = jQuery("#databaseClasses").jqGrid(
							'getGridParam', 'selrow');
					if (selectedRow != null) {
						selObject = jQuery('#databaseClasses').jqGrid(
								'getRowData', selectedRow)["name"];

						controller.loadFragment("panelDocument.htm",
								function() {
									documentView.create(selObject);
								});
					}
				});
		fillDynaTable($('#databaseConfig'), "Configuration",
				[ 'name', 'value' ], null, databaseInfo['config'].values, {
					sortname : 'name'
				});

		fillDynaTable($('#databaseConfigProperties'),
				"Configuration properties", [ 'name', 'value' ], null,
				databaseInfo['config'].properties, {
					sortname : 'name'
				});
		
		$("#exportDatabase").click(
                function() {
                	orientServer.open();
                    var exportUrl = orientServer.getDatabaseUrl() + "export/" + orientServer.getDatabaseName();
                    window.open(exportUrl,'Download');
                });
	}

	function askDatabaseInfo() {
		databaseInfo = orientServer.open();
		if (databaseInfo == null) {
			jQuery("#output").text(orientServer.getErrorMessage());
		} else {
			showDatabaseInfo();
		}
	}

	function formatFileSize(size) {
		if (size > 1000000000)
			return Math.round(size / 10000000) / 100 + " Tb";
		else if (size > 1000000)
			return Math.round(size / 1000000) / 100 + " Mb";
		else if (size > 1000)
			return Math.round(size / 1000) / 100 + " Kb";
		return size + " b";
	}

	function Graph(canvas, size) {
		this.canvas = canvas;
		this.size = size;

		this.gridSize = this.canvas.width * this.canvas.height;
		this.pixelFactor = size / this.gridSize;
		this.context = canvas.getContext("2d");
		this.xpadding = 0;
		this.ypadding = 0;
		this.block = this.canvas.width;
		this.rows = this.canvas.height;
		this.unitWidthPx = this.canvas.width / this.block - this.xpadding * 2;
		this.unitHeightPx = this.canvas.height / this.rows - this.ypadding * 2;
		this.cursor = 0;
		this.cursorRow = 0;

		this.fill = function(size, color) {
			this.context.fillStyle = color;
			var baseSize = size / this.pixelFactor;
			do {
				if (this.cursor + baseSize >= this.block) {
					var x = this.getPx(this.cursor, this.unitWidthPx,
							this.xpadding)
							+ this.xpadding;
					var y = this.getPx(this.cursorRow, this.unitHeightPx,
							this.ypadding);
					var w = this.getPx(this.block - this.cursor,
							this.unitWidthPx, this.xpadding)
							- this.xpadding;
					this.context.fillRect(x, y, w, this.unitHeightPx);
					baseSize = baseSize - (this.block - this.cursor);
					this.cursor = 0;
					this.cursorRow++;
				} else {
					var x = this.getPx(this.cursor, this.unitWidthPx,
							this.xpadding)
							+ this.xpadding;
					var y = this.getPx(this.cursorRow, this.unitHeightPx,
							this.ypadding);
					var w = this.getPx(baseSize, this.unitWidthPx,
							this.xpadding)
							- this.xpadding;
					this.context.fillRect(x, y, w, this.unitHeightPx);
					this.cursor += baseSize;
					baseSize = 0;
				}

			} while (baseSize > 0);
		}
		this.close = function(color) {
			var size = this.block - this.cursor;
			size += this.rows * this.block;
			this.fill(size, color);
		}
		this.getPx = function(pos, size, padding) {
			var paddingSize = padding * 2 * pos;
			var ogbjectSize = pos * size;
			return paddingSize + ogbjectSize;
		}
	}

	$('#tabs-db')
			.tabs(
					{
						select : function(event, ui) {
							if (ui.tab.textContent.indexOf('Allocation') > -1) {
								$
										.ajax({
											type : "GET",
											url : urlPrefix
													+ 'allocation/'
													+ $('#header-database')
															.val(),
											context : this,
											async : false,
											success : function(alloc) {
												if (alloc != null) {
													var canv = document
															.getElementById("allocation-canvas");
													var ff = new Graph(canv,
															alloc.size);

													for (i in alloc.segments) {
														var segment = alloc.segments[i];

														if (segment.type == 'd') {
															ff
																	.fill(
																			segment.size,
																			'#00FF00');
														} else {
															ff
																	.fill(
																			segment.size,
																			'#FF0000');
														}
													}

													$('#data-value')
															.text(
																	formatFileSize(alloc.dataSize)
																			+ ' ('
																			+ alloc.dataSizePercent
																			+ '%)');
													$('#holes-value')
															.text(
																	formatFileSize(alloc.holesSize)
																			+ ' ('
																			+ alloc.holesSizePercent
																			+ '%)');
												}
											},
											error : function(msg) {
												var canv = $("#allocation-data");
												canv.empty();
												canv
														.append("Error on retrieving database's allocation table");
											}
										});

							}
						}
					});
	$('#tabs-security').tabs();
	
	$('#importDatabase').fileUploadUI({
		url: orientServer.getDatabaseUrl() + 'import/' + orientServer.getDatabaseName(),
		uploadTable: $('#importFileUploadTable'),
		downloadTable: $('#importFileDownloadTable'),
		buildUploadRow: function() {
			orientServer.open();
			return $('<tr>' +
			'<td class="file_upload_progress"><div><\/div><\/td>' +
			'<td class="file_upload_cancel">' +
			'<button class="ui-state-default ui-corner-all" title="Cancel">' +
			'<span class="ui-icon ui-icon-cancel">Cancel<\/span>' +
			'<\/button>' +
			'<\/td>' +
			'<\/tr>');
		},
		buildDownloadRow: function(response) {
			var responseText = response.responseText;
			jQuery('#output').val(responseText);
		}
	});
	showDatabaseInfo();
</script>